package com.baby.movie.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.baby.movie.R;
import com.baby.movie.util.Constants;
import com.baby.movie.util.ImageUtil;

public class MainActivity extends BaseActivity {
	
	private static final String[] TAGS = {"tab1", "tab2", "tab3", "tab4"};
	
	private Fragment[] mFragments;
	
	private RadioGroup mTabs;


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
		case R.id.action_search:
			Intent intent = new Intent(this, SearchActivity.class);
			intent.putExtra(Constants.CATEGOTY, 1);
			startActivity(intent);
			break;

		default:
			break;
		}
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	ImageUtil.init(this);
    }

	@Override
	protected int getContentViewRes() {
		return R.layout.activity_main;
	}


	@Override
	protected void findViews() {
		mTabs = (RadioGroup) findViewById(R.id.tabs);
	}


	@Override
	protected void initialize() {
		mFragments = new Fragment[4];
		
		mTabs.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int position = 0;
				String tag;
				
				switch (checkedId) {
				case R.id.tab1:
					position = 0;
					break;
				case R.id.tab2:
					position = 1;
					break;
				case R.id.tab3:
					position = 2;
					break;
				case R.id.tab4:
					position = 3;
					break;

				default:
					position = 0;
					break;
				}
				tag = TAGS[position];
				Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
				if (null == fragment) {
					fragment = new MTFragment();
					mFragments[position] = fragment;
					addFragment(fragment, tag);
				}
				
				showFragment(fragment);
			}
		});
		
		RadioButton tab1 = (RadioButton) findViewById(R.id.tab1);
		tab1.setChecked(true);
	}
	
	private void addFragment(Fragment fragment, String tag) {
		getSupportFragmentManager().beginTransaction()
		.add(R.id.fragmentContainenr, fragment, tag)
		.commit();
	}
	
	private void showFragment(Fragment fragment) {
		FragmentTransaction transaction =  getSupportFragmentManager().beginTransaction();
		for (Fragment f : mFragments) {
			if (null != f) {
				transaction.hide(f);
			}
		}
		transaction.show(fragment)
		.commit();
	}
	
	@Override
	protected void onDestroy() {
		ImageUtil.clearCache();
		super.onDestroy();
	}
}
